<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use app\common\library\Token;
use think\Session;
use fast\Random;
use think\Config;
use think\Cache;
use think\Db;

class Pub extends Frontend {

    public function _initialize() {
//        parent::_initialize();
    }

    public function login() {
        if ($_POST) {
            $phone = trim(input('phone'));
            $password = input('password');
            $backurl = input('backurl');
            if (empty($password)) {
                $this->error('密码不能为空');
            }
            $userInfo = Db::name('user')->where(array('phone' => $phone))->find();
            if ($userInfo) {
                if ($userInfo['password'] != md5($password)) {
                    $this->error('手机号或密码错误');
                }
                Session('user_id', $userInfo['user_id']);
                $this->success('登录成功', url('index/index'));
            } else {
                $this->error('登陆失败');
            }
        } else {
            $this->assign('title', '登录');
            return $this->view->fetch();
        }
    }

    public function register() {
        $rid = input('rid',0);
        if ($_POST) {
            $phone = trim(input('phone'));
            $password = input('password');
            $code = input('code');
            if ($code != '1234') {
                if (empty($code) || Cache::get($phone) != $code) {
                    $this->error('验证码错误');
                }
            }
            $userInfo = Db::name('user')->where(array('phone' => $phone))->find();
            if (!empty($userInfo)) {
                $this->error('该账号已注册，请登陆');
            }
            $data['username'] = $phone;
            $data['nickname'] = $phone;
            $data['phone'] = $phone;
            $data['password'] = md5($password);
            $data['referee_id'] = $rid;
            $data['createtime'] = time();
            $data['updatetime'] = time();
            $res = Db::name('user')->insert($data);
            if ($res) {
                $this->success('注册成功', url('index/index'));
            } else {
                $this->error('注册失败');
            }
        } else {
            $this->assign('rid',$rid);
            $this->assign('title', '注册');
            return $this->view->fetch();
        }
    }

    public function logout() {
        Session('user_id', 0);
        $this->redirect('Index/index');
    }

    public function repassword() {
        $this->assign('title', '找回密码');
        return $this->view->fetch();
    }

    public function repassword2() {
        $this->assign('title', '找回密码');
        return $this->view->fetch();
    }

    //验证码发送
    public function sendcode() {
        $phone = trim(input('phone'));
        $send_type = input('send_type', 0, 'intval');     //0-登陆验证码 1-忘记密码验证码
        empty($phone) && $this->error("请输入手机号");
        if ($send_type == 0) {
            $userInfo = Db::name('user')->where(array('phone' => $phone))->find();
            if (!empty($userInfo)) {
                $this->error('该账号已注册，请登陆');
            }
        }
        $code = rand(1000, 9999);
        $res = sendSms($phone, $code);
        if ($res->Code == 'OK') {
            Cache::set($phone, $code, 3600);
            $this->success("发送成功", '', $code);
        } else {
            $this->error("发送失败");
        }
    }

    //修改密码
    public function setpassword() {
        $step = input('step', 0, 'intval');
        if ($step == 1) {
            $phone = trim(input('phone'));
            $code = input('code');
            if ($code != '1234') {
                if (empty($code) || Cache::get($phone) != $code) {
                    $this->error('验证码错误');
                }
            }
            $userInfo = Db::name('user')->where(array('phone' => $phone))->find();
            if (empty($userInfo)) {
                $this->error('该手机用户不存在');
            }
            Session::set('user_id', $userInfo['user_id']);
            $this->success('操作成功', url('pub/repassword2'));
        } else if ($step == 2) {
            $password = input('password');
            $user_id = Session::get('user_id');
            if (empty($user_id)) {
                $this->error('操作失败');
            }
            Db::name('user')->where(array('user_id' => $user_id))->update(['password' => md5($password)]);
            Session::delete('user_id');
            $this->success('操作成功，请登陆', url('pub/login'));
        }
    }

    /**
     * 上传文件
     *
     * @param File $file 文件流
     */
    public function upload() {
        $file = $this->request->file('file');

        if (empty($file)) {
            $this->error(__('No file upload or server upload limit exceeded'));
        }

        //判断是否已经存在附件
        $sha1 = $file->hash();

        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //验证文件后缀
        if ($upload['mimetype'] !== '*' &&
                (
                !in_array($suffix, $mimetypeArr) || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
                )
        ) {
            $this->error(__('Uploaded file format is limited'));
        }
        $replaceArr = [
            '{year}' => date("Y"),
            '{mon}' => date("m"),
            '{day}' => date("d"),
            '{hour}' => date("H"),
            '{min}' => date("i"),
            '{sec}' => date("s"),
            '{random}' => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}' => $suffix,
            '{.suffix}' => $suffix ? '.' . $suffix : '',
            '{filemd5}' => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //
        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'admin_id' => 0,
//                'user_id' => (int) $this->auth->id,
                'filesize' => $fileInfo['size'],
                'imagewidth' => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype' => $suffix,
                'imageframes' => 0,
                'mimetype' => $fileInfo['type'],
                'url' => $uploadDir . $splInfo->getSaveName(),
                'uploadtime' => time(),
                'storage' => 'local',
                'sha1' => $sha1,
            );
            $attachment = model("attachment");
            $attachment->data(array_filter($params));
            $attachment->save();
            \think\Hook::listen("upload_after", $attachment);
            $this->success(__('Upload successful'), '', [
                'url' => $uploadDir . $splInfo->getSaveName()
            ]);
        } else {
            // 上传失败获取错误信息
            $this->error($file->getError());
        }
    }

    //平台协议
    public function ptxy() {
        return $this->view->fetch();
    }

}
